import React from 'react'
import {Card, Button, Modal, Form, Select, Input, Radio, DatePicker, message} from 'antd'
import Axios from '../../../axios'
import JustTable from '../../../components/JustTable'
import JustForm from '../../../components/BaseForm'
import Utils from "../../../utils/utils";
import moment from "moment";

const FormItem = Form.Item
const RadioGroup = Radio.Group
const TextArea = Input.TextArea
const Option = Select.Option
export default class User extends React.Component {
    state = {
        itemList: [],
        isVisible: false
    }
    params = {
        page: 1
    }
    formList = [
        {
            type: 'INPUT',
            label: '用户名',
            field: 'user_name',
            placeholder: '请输入用户名',
            width: 100,
        },
        {
            type: 'INPUT',
            label: '手机号',
            field: 'user_phone',
            placeholder: '请输入用户手机号',
            width: 100,
        },
        {
            type: 'DATE',
            label: '入职时间',
            field: ['join_time'],
            showTime: true,
            placeholder: '请输选择入职时间',
            width: 100,
        },
    ]

    componentDidMount() {
        this.requestList()
    }

    requestList() {
        Axios.requestList(this, '/user/list', this.params, true)
    }

    filterSubmit = (params) => {
        //合并参数 解构顺序不能错,变量覆盖
        this.params = {...this.params, ...params}
        this.requestList()
    }



    handleOperate = (type) => {
        console.log(type)
        let item = this.state.selectedItem
        if (type == 'create') {
            this.setState({
                type,
                isVisible: true,
                title: '添加用户'
            })
        } else if (type == 'edit') {
            if (!item) {
                return Modal.error({
                    title: '提示',
                    content: '请选择用户!'
                })
            }
            this.setState({
                type,
                isVisible: true,
                title: '编辑用户',
                userInfo: item,
            })
        } else if (type == 'detail') {
            if (!item) {
                return Modal.error({
                    title: '提示',
                    content: '请选择用户!'
                })
            }
            this.setState({
                type,
                isVisible: true,
                title: '用户详情',
                userInfo: item,
            })
        } else if (type == 'delete') {
            if (!item) {
                return Modal.error({
                    title: '提示',
                    content: '请选择用户!'
                })
            }
            Modal.confirm({
                title: '确认删除?',
                onOk: () => { //使用箭头函数,this作用于暴露处理
                    Axios.ajax({
                        url: '/city/open',
                        method: 'get',
                        data: {
                            id: item.id
                        }
                    }).then((res) => {
                        if (res.code == 0) {
                            message.success(`删除成功`)
                            this.handleModalHide()
                            this.requestList()
                        }
                    })
                }
            })
        }
    }
    handleModalSubmit = () => {
        console.log('handleModalSubmit')
        let userInfo = this.modalForm.props.form.getFieldsValue()
        console.log(userInfo)
        this.modalForm.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                Axios.ajax({
                    url: this.state.type = 'create' ? '/city/open' : '/city/open?edit',
                    data: userInfo,
                    method: 'post'
                }).then((res) => {
                    console.log(res)
                    if (res.code == 0) {
                        this.state.type = 'create' ? message.success(`添加成功`) : message.success(`编辑成功`)
                        this.handleModalHide()
                        this.requestList()
                    }
                })
            }
        });
    }
    handleModalHide = () => {
        this.modalForm && this.modalForm.props.form.resetFields();
        this.setState({
            isVisible: false,
            type: null,
            title: '',
            selectedRowKeys: null,
            selectedItem: null,
            selectedIds: null,
            userInfo: {}
        })
    }

    render() {
        const columns = [
            {
                title: 'ID',
                dataIndex: 'id',
            },
            {
                title: '用户名',
                dataIndex: 'usename',
            },
            {
                title: '真实姓名',
                dataIndex: 'real_name',
            },
            {
                title: '性别',
                dataIndex: 'sex',
                render(record) {
                    return record.sex == 0 ? '未知' : (record.sex == 1 ? '男' : '女');
                }
            },
            {
                title: '年龄',
                dataIndex: 'age',
            },
            // {
            //     title:'上次登录时间',
            //     dataIndex:'city_admins',
            //     render(record){
            //         return record.map((item)=>{
            //             return item.user_name
            //         }).join(',')
            //     }
            // },
            {
                title: '上次登录时间',
                dataIndex: 'last_time',
            },
            // {
            //     title:'操作时间',
            //     dataIndex:'update_time',
            //     render:Utils.formatDate
            // },
            // {
            //     title:'操作人',
            //     dataIndex:'sys_user_name',
            // },
        ]

        //footer不太方便直接设置,可以通过解构方式设置footer
        let footer = {}
        if (this.state.type == 'detail') {
            footer = {
                footer: null
            }
        }
        return (
            <div>
                <Card>
                    <JustForm
                        formList={this.formList}
                        filterSubmit={this.filterSubmit}
                    />
                </Card>
                <Card className={"operate-wrap"}>
                    <Button type={'primary'} icon={'plus'} onClick={() => {
                        this.handleOperate('create')
                    }}>添加用户</Button>
                    <Button type={'primary'} icon={'edit'} onClick={() => {
                        this.handleOperate('edit')
                    }}>编辑用户</Button>
                    <Button type={'primary'} onClick={() => {
                        this.handleOperate('detail')
                    }}>用户详情</Button>
                    <Button type={'primary'} icon={'delete'} onClick={() => {
                        this.handleOperate('delete')
                    }}>删除用户</Button>
                </Card>
                <div className={"content-wrap"}>
                    <JustTable
                        columns={columns}
                        dataSource={this.state.itemList}
                        pagination={this.state.pagination}
                        // rowSelection = {'checkbox'}
                        rowSelection={'radio'}
                        selectedRowKeys={this.state.selectedRowKeys}
                        selectedItem={this.state.selectedItem}
                        selectedIds={this.state.selectedIds}
                        updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                    />
                </div>

                <Modal
                    title={this.state.title}
                    visible={this.state.isVisible}
                    onOk={this.handleModalSubmit}
                    onCancel={this.handleModalHide}
                    destroyOnClose={true}
                    {...footer}
                >
                    <UserForm
                        type={this.state.type}
                        userInfo={this.state.userInfo}
                        wrappedComponentRef={(form) => {
                            this.modalForm = form
                        }}
                    />
                </Modal>
            </div>
        )
    }
}

class UserForm extends React.Component {

    render() {
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 19}
        }
        const {getFieldDecorator} = this.props.form

        const type = this.props.type
        const userInfo = this.props.userInfo || {}
        console.log(userInfo)
        return (
            <Form layout='horizontal' {...formItemLayout}>
                <FormItem label='用户名'>
                    {
                        type == 'detail' ? userInfo.usename :
                            getFieldDecorator('usename', {
                                initialValue: userInfo.usename,
                                placeholder: '请输入用户名'
                            })(
                                <Input/>
                            )
                    }
                </FormItem>
                <FormItem label='性别'>
                    {
                        type == 'detail' ? (userInfo.sex == 1 ? '男' : '女') :
                            getFieldDecorator('sex', {
                                initialValue: userInfo.sex,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择性别'
                                    }
                                ]
                            })(
                                <RadioGroup>
                                    <Radio value={0}>未知</Radio>
                                    <Radio value={1}>男</Radio>
                                    <Radio value={2}>女</Radio>
                                </RadioGroup>
                            )
                    }
                </FormItem>
                <FormItem label='状态'>
                    {
                        type == 'detail' ? userInfo.status :
                            getFieldDecorator('status', {
                                initialValue: userInfo.status,
                            })(
                                <Select>
                                    <Option value={0}>待审核</Option>
                                    <Option value={1}>已审核</Option>
                                    <Option value={2}>不通过</Option>
                                </Select>
                            )
                    }
                </FormItem>
                <FormItem label='生日'>
                    {
                        type == 'detail' ? userInfo.birthday :
                            getFieldDecorator('date', {
                                initialValue: moment(userInfo.birthday)
                            })(
                                <DatePicker/>
                            )
                    }
                </FormItem>
                <FormItem label='地址'>
                    {
                        type == 'detail' ? userInfo.address :
                            getFieldDecorator('address', {
                                initialValue: userInfo.address
                            })(
                                <TextArea rows={4}/>
                            )
                    }
                </FormItem>
            </Form>
        )
    }
}

UserForm = Form.create({})(UserForm)
